package com.example.qundui.learndemo.blooath;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.qundui.learndemo.R;
import com.example.qundui.learndemo.lvtest.bases;

import java.io.IOException;

/**
 * Created by qundui on 2017/5/5.
 */

public class BTest extends bases {
    @Override
    protected void doBusy() {

    }
    public void open(View view){
        BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();

        if (!defaultAdapter.isEnabled()){
            defaultAdapter.enable();
            Toast.makeText(this,"open",Toast.LENGTH_SHORT).show();
        }
      else{
            Toast.makeText(this," 已经打开",Toast.LENGTH_SHORT).show();
            defaultAdapter.startDiscovery();
        }
    }
    public void tauch(View view){


    }
    public void createBond(BluetoothDevice btDev, Handler handler) {
        if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
            //如果这个设备取消了配对，则尝试配对
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //安卓版本大于等于4.3
                btDev.createBond();
            }
        } else if (btDev.getBondState() == BluetoothDevice.BOND_BONDED) {
            //如果这个设备已经配对完成，则尝试连接
            connect(btDev, handler);
        }
    }
    private void connect(BluetoothDevice btDev, Handler handler) {
//        try {
//            //通过和服务器协商的uuid来进行连接
//            mBluetoothSocket = btDev.createRfcommSocketToServiceRecord(BltContant.SPP_UUID);
//            if (mBluetoothSocket != null)
//                //全局只有一个bluetooth，所以我们可以将这个socket对象保存在appliaction中
//                BltAppliaction.bluetoothSocket = mBluetoothSocket;
//
//            Log.i("blueTooth", "开始连接...");
//            //在建立之前调用
//            if (getmBluetoothAdapter().isDiscovering())
//                //停止搜索
//                getmBluetoothAdapter().cancelDiscovery();
//            //如果当前socket处于非连接状态则调用连接
//            if (!getmBluetoothSocket().isConnected()) {
//                //你应当确保在调用connect()时设备没有执行搜索设备的操作。
//                // 如果搜索设备也在同时进行，那么将会显著地降低连接速率，并很大程度上会连接失败。
//                getmBluetoothSocket().connect();
//            }
//            Log.i("blueTooth", "已经连接");
//            if (handler == null) return;
//            //结果回调
//            Message message = new Message();
//            message.what = 4;
//            message.obj = btDev;
//            handler.sendMessage(message);
//        } catch (Exception e) {
//            Log.i("blueTooth", "...连接失败");
//            try {
//                getmBluetoothSocket().close();
//            } catch (IOException e1) {
//                e1.printStackTrace();
//            }
//            e.printStackTrace();
//        }
    }
    @Override
    protected int getLayout() {
        return R.layout.bt;
    }
}
